package com.ims.framework.aspectj;

import com.ims.common.annotation.DataScope;
import com.ims.common.annotation.RequestName;
import com.ims.common.annotation.RequestParamsSplit;
import com.ims.common.core.domain.BaseEntity;
import com.ims.common.core.domain.entity.SysRole;
import com.ims.common.core.domain.entity.SysUser;
import com.ims.common.core.domain.model.LoginUser;
import com.ims.common.core.text.Convert;
import com.ims.common.utils.SecurityUtils;
import com.ims.common.utils.StringUtils;
import com.ims.framework.security.context.PermissionContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 列表查询参数 searchValues 解析处理
 * @author IMS
 */
@Aspect
@Component
public class RequestParamsSplitAspect
{

    @Before("@annotation(requestParamsSplit)")
    public void doBefore(JoinPoint point, RequestParamsSplit requestParamsSplit) throws Throwable
    {
        // 获取参数中的 searchValues 值
        Object params = point.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
        {
            BaseEntity baseEntity = (BaseEntity) params;
            List<Object[]> fields = getFields(baseEntity.getClass());
            String[] searchValues = baseEntity.getSearchValues();
            if(searchValues != null && searchValues.length > 0){
                for(String keyValue : searchValues){
                    String key = keyValue.split(":")[0];
                    String value = keyValue.split(":")[1];
                    for(Object[] object : fields){
                        Field field = (Field)object[0];
                        String name = (String)object[1];
                        if(key.equals(name)){
                            field.setAccessible(true);
                            field.set(baseEntity, value);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取字段注解信息
     */
    public List<Object[]> getFields(Class clazz)
    {
        List<Object[]> fields = new ArrayList<Object[]>();
        List<Field> tempFields = new ArrayList<>();
        tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
        tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
        for (Field field : tempFields)
        {
            RequestName attr = field.getAnnotation(RequestName.class);
            if(attr != null){
                fields.add(new Object[] { field, attr.name() });
            }
        }
        return fields;
    }

}
